/**
 * API工具类 - 统一管理云函数调用
 * 宠物门店预约小程序
 */

const setting = require('../setting/setting.js');
const cacheManager = require('./cache-manager.js');

class ApiService {
  constructor() {
    this.baseUrl = 'cloud'; // 云函数名称
    this.requestQueue = new Map(); // 请求队列，防止重复请求
    this.concurrentLimit = 5; // 并发请求限制
    this.activeRequests = 0; // 当前活跃请求数
  }

  /**
   * 调用云函数（带缓存和并发控制）
   * @param {string} service 服务名称
   * @param {string} action 操作名称
   * @param {Object} data 请求数据
   * @param {Object} options 选项 {cache: boolean, ttl: number, forceRefresh: boolean}
   * @returns {Promise} 返回结果
   */
  async callFunction(service, action, data = {}, options = {}) {
    const {
      cache = false,
      ttl = 5 * 60 * 1000, // 5分钟缓存
      forceRefresh = false
    } = options;

    // 生成缓存键
    const cacheKey = `${service}_${action}_${JSON.stringify(data)}`;
    
    // 检查缓存
    if (cache && !forceRefresh) {
      const cachedData = cacheManager.get(cacheKey);
      if (cachedData) {
        return cachedData;
      }
    }

    // 检查是否有相同的请求正在进行
    if (this.requestQueue.has(cacheKey)) {
      console.log(`[API] 等待重复请求: ${service}/${action}`);
      return await this.requestQueue.get(cacheKey);
    }

    // 控制并发数
    if (this.activeRequests >= this.concurrentLimit) {
      console.log(`[API] 并发限制，等待请求: ${service}/${action}`);
      await this.waitForSlot();
    }

    // 创建请求Promise
    const requestPromise = this.executeRequest(service, action, data, cacheKey, cache, ttl);
    
    // 添加到请求队列
    this.requestQueue.set(cacheKey, requestPromise);
    
    try {
      const result = await requestPromise;
      return result;
    } finally {
      // 清理请求队列
      this.requestQueue.delete(cacheKey);
      this.activeRequests--;
    }
  }

  /**
   * 执行实际的云函数请求
   */
  async executeRequest(service, action, data, cacheKey, useCache, ttl) {
    this.activeRequests++;
    
    try {
      // 获取当前用户ID，确保所有API请求都携带用户身份信息
      const userId = wx.getStorageSync('userId');
      const token = wx.getStorageSync('token');
      
      // 检测调用来源，如果是从商家端页面调用，添加来源标识
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const route = currentPage ? currentPage.route : '';
      const isFromMerchant = route && route.includes('merchant/');
      
      // 构建请求数据，包含用户认证信息
      const requestData = {
        service,
        action,
        userId: userId || null,
        token: token || null,
        _callFrom: isFromMerchant ? 'merchant' : 'user', // 标记调用来源
        ...data
      };
      
      const result = await wx.cloud.callFunction({
        name: this.baseUrl,
        data: requestData
      });

      console.log(`API调用: ${service}/${action}`, { data, result });
      console.log('=== API工具类 - 云函数返回详情 ===');
      console.log('result.result:', result.result);
      console.log('result.result.code:', result.result?.code);
      console.log('result.result.data:', result.result?.data);
      console.log('result.result.msg:', result.result?.msg);

      // 处理云函数返回的响应格式
      const response = result.result;
      let apiResult;
      
      if (response && response.code === 200) {
        apiResult = {
          success: true,
          data: response.data || [],
          message: response.msg || 'success'
        };
      } else {
        console.error('API调用失败:', {
          service,
          action,
          code: response?.code,
          msg: response?.msg,
          data: response?.data
        });
        apiResult = {
          success: false,
          message: response?.msg || response?.message || '请求失败',
          code: response?.code || -1
        };
      }

      // 缓存成功的结果
      if (useCache && apiResult.success) {
        cacheManager.set(cacheKey, apiResult, ttl);
      }

      return apiResult;
    } catch (error) {
      console.error(`API调用失败: ${service}/${action}`, error);
      return {
        success: false,
        message: error.message || '网络请求失败',
        code: -1
      };
    }
  }

  /**
   * 等待请求槽位
   */
  async waitForSlot() {
    return new Promise(resolve => {
      const checkSlot = () => {
        if (this.activeRequests < this.concurrentLimit) {
          resolve();
        } else {
          setTimeout(checkSlot, 50);
        }
      };
      checkSlot();
    });
  }

  // ==================== 用户相关API ====================

  /**
   * 用户登录
   * @param {string} code 微信登录code
   * @param {Object} userInfo 用户信息
   */
  async login(code, userInfo = {}) {
    const result = await this.callFunction('passport', 'login', {
      code,
      nickName: userInfo.nickName,
      avatarUrl: userInfo.avatarUrl
    });
    
    // 登录成功后保存用户信息到本地存储
    if (result.success && result.data) {
      // 兼容两种返回结构：优先使用 userInfo._id，其次回退到顶层 userId
      const userData = result.data.userInfo;
      const token = result.data.token;
      const uid = (userData && userData._id) ? userData._id : (result.data.userId || null);
      if (uid) {
        wx.setStorageSync('userId', uid);
      }
      if (token) {
        wx.setStorageSync('token', token);
      }
      if (userData) {
        wx.setStorageSync('userInfo', userData);
      }
    }
    
    return result;
  }

  /**
   * 获取用户详情
   */
  async getUserDetail() {
    return await this.callFunction('passport', 'my_detail');
  }

  /**
   * 获取手机号
   * @param {string} cloudID 云函数ID
   */
  async getPhone(cloudID) {
    return await this.callFunction('passport', 'get_phone', { cloudID });
  }

  /**
   * 编辑用户基本信息
   * @param {Object} userData 用户数据
   */
  async editUserBase(userData) {
    return await this.callFunction('passport', 'edit_base', userData);
  }

  /**
   * 更新用户信息
   * @param {Object} userInfo 用户信息
   */
  async updateUserInfo(userInfo) {
    return await this.callFunction('passport', 'update_user_info', userInfo);
  }

  /**
   * 更新用户余额
   * @param {number} amount 更新金额（分）
   */
  async updateBalance(amount) {
    return await this.callFunction('passport', 'update_balance', { amount });
  }

  /**
   * 获取宠物列表（带缓存）
   */
  async getPetList(forceRefresh = false) {
    return await this.callFunction('pet', 'list', {}, {
      cache: true,
      ttl: 3 * 60 * 1000, // 3分钟缓存
      forceRefresh
    });
  }

  /**
   * 获取宠物详情
   * @param {string} petId 宠物ID
   */
  async getPetDetail(petId) {
    return await this.callFunction('pet', 'detail', { petId });
  }

  /**
   * 添加宠物
   * @param {Object} petData 宠物数据
   */
  async addPet(petData) {
    return await this.callFunction('pet', 'add', petData);
  }

  /**
   * 更新宠物信息
   * @param {string} petId 宠物ID
   * @param {Object} petData 宠物数据
   */
  async updatePet(petId, petData) {
    return await this.callFunction('pet', 'update', { petId, ...petData });
  }

  /**
   * 删除宠物
   * @param {string} petId 宠物ID
   */
  async deletePet(petId) {
    return await this.callFunction('pet', 'delete', { petId });
  }

  /**
   * 获取宠物统计
   */
  async getPetStats() {
    return await this.callFunction('pet', 'stats');
  }

  /**
   * 获取门店列表
   * @param {number} longitude 经度
   * @param {number} latitude 纬度
   * @param {number} radius 半径（公里）
   */
  async getStoreList(longitude, latitude, radius = 10) {
    return await this.callFunction('store', 'list', { longitude, latitude, radius });
  }

  /**
   * 获取门店详情
   * @param {string} storeId 门店ID
   */
  async getStoreDetail(storeId) {
    return await this.callFunction('store', 'detail', { storeId });
  }

  /**
   * 添加门店
   * @param {Object} storeData 门店数据
   */
  async addStore(storeData) {
    return await this.callFunction('store', 'add', storeData);
  }

  /**
   * 更新门店信息
   * @param {string} storeId 门店ID
   * @param {Object} storeData 门店数据
   */
  async updateStore(storeId, storeData) {
    return await this.callFunction('store', 'update', { storeId, ...storeData });
  }

  /**
   * 获取门店服务列表
   * @param {string} storeId 门店ID
   */
  async getStoreServices(storeId) {
    return await this.callFunction('store', 'services', { storeId });
  }

  /**
   * 获取门店寄养房间列表
   * @param {string} storeId 门店ID
   */
  async getStoreFosterRooms(storeId) {
    return await this.callFunction('store', 'foster_rooms', { storeId });
  }

  /**
   * 创建预约
   * @param {Object} appointmentData 预约数据
   */
  async createAppointment(appointmentData) {
    return await this.callFunction('appointment', 'create', appointmentData);
  }

  /**
   * 获取我的预约
   * @param {number} status 状态
   * @param {number} page 页码
   * @param {number} size 每页数量
   */
  async getMyAppointments(status = null, page = 1, size = 20) {
    return await this.callFunction('appointment', 'list', { status, page, size });
  }

  /**
   * 获取预约详情
   * @param {string} appointmentId 预约ID
   */
  async getAppointmentDetail(appointmentId) {
    return await this.callFunction('appointment', 'detail', { appointmentId });
  }

  /**
   * 更新预约状态
   * @param {string} appointmentId 预约ID
   * @param {number} status 新状态
   */
  async updateAppointmentStatus(appointmentId, status) {
    return await this.callFunction('appointment', 'update_status', {
      appointmentId,
      status
    });
  }

  /**
   * 取消预约
   * @param {string} appointmentId 预约ID
   */
  async cancelAppointment(appointmentId) {
    return await this.callFunction('appointment', 'cancel', { appointmentId });
  }

  /**
   * 删除预约（软删除，仅限已取消的订单）
   * @param {string} appointmentId 预约ID
   */
  async deleteAppointment(appointmentId) {
    return await this.callFunction('appointment', 'delete', { appointmentId });
  }

  // ==================== 支付相关API ====================

  /**
   * 创建支付订单（云函数版本）
   * @param {string} appointmentId 预约ID
   */
  async createPayment(appointmentId) {
    // 如果启用自建后端支付，则调用自建后端接口返回支付参数
    if (setting.USE_SELF_BACKEND_PAYMENT && setting.API_BASE) {
      const js_code = await this.getWxLoginCode().catch(() => '');
      return await this.httpPost('/api/payment/create', { appointmentId, js_code });
    }
    // 默认走云函数
    return await this.callFunction('payment', 'create', { appointmentId });
  }

  /**
   * 处理支付回调
   * @param {string} appointmentId 预约ID
   * @param {Object} paymentResult 支付结果
   */
  async handlePaymentCallback(appointmentId, paymentResult) {
    if (setting.USE_SELF_BACKEND_PAYMENT && setting.API_BASE) {
      return await this.httpPost('/api/payment/callback', { appointmentId, ...paymentResult });
    }
    return await this.callFunction('payment', 'callback', {
      appointmentId,
      ...paymentResult
    });
  }



  /**
   * 余额支付
   * @param {string} appointmentId 预约ID
   */
  async payWithBalance(appointmentId) {
    return await this.callFunction('payment', 'balance', { appointmentId });
  }

  /**
   * 申请退款
   * @param {string} appointmentId 预约ID
   * @param {string} reason 退款原因
   */
  async requestRefund(appointmentId, reason) {
    return await this.callFunction('payment', 'refund', {
      appointmentId,
      reason
    });
  }

  /**
   * 获取交易记录
   * @param {number} page 页码
   * @param {number} size 每页数量
   */
  async getTransactionRecords(page = 1, size = 20) {
    return await this.callFunction('payment', 'records', {
      page,
      size
    });
  }

  // ==================== 充值相关API ====================

  /**
   * 创建充值订单
   * @param {number} amount 充值金额（分）
   * @param {number} bonus 赠送金额（分）
   * @param {string} packageId 充值套餐ID
   */
  async createRechargeOrder(amount, bonus = 0, packageId = '') {
    if (setting.USE_SELF_BACKEND_PAYMENT && setting.API_BASE) {
      const js_code = await this.getWxLoginCode().catch(() => '');
      return await this.httpPost('/api/recharge/create_order', { amount, bonus, packageId, js_code });
    }
    return await this.callFunction('payment', 'create_recharge_order', {
      amount,
      bonus,
      packageId
    });
  }

  /**
   * 处理充值支付回调
   * @param {string} rechargeOrderId 充值订单ID
   * @param {Object} paymentResult 支付结果
   */
  async handleRechargeCallback(rechargeOrderId, paymentResult) {
    if (setting.USE_SELF_BACKEND_PAYMENT && setting.API_BASE) {
      return await this.httpPost('/api/recharge/callback', { rechargeOrderId, ...paymentResult });
    }
    return await this.callFunction('payment', 'recharge_callback', {
      rechargeOrderId,
      ...paymentResult
    });
  }

  /**
   * 获取用户充值记录
   * @param {number} page 页码
   * @param {number} size 每页数量
   */
  async getUserRechargeRecords(page = 1, size = 20) {
    return await this.callFunction('payment', 'recharge_records', {
      page,
      size
    });
  }

  // ==================== 优惠券相关API ====================

  /**
   * 获取用户优惠券列表
   * @param {number} status 状态筛选 1:未使用, 2:已使用, 3:已过期
   * @param {number} page 页码
   * @param {number} size 每页数量
   */
  async getUserCoupons(status = null, page = 1, size = 20) {
    return await this.callFunction('coupon', 'list', {
      status,
      page,
      size
    });
  }

  /**
   * 使用优惠券
   * @param {string} couponId 优惠券ID
   * @param {string} appointmentId 预约ID
   */
  async useCoupon(couponId, appointmentId) {
    return await this.callFunction('coupon', 'use', {
      couponId,
      appointmentId
    });
  }

  /**
   * 获取可用优惠券列表（用于下单时选择）
   * @param {number} amount 订单金额（分）
   * @param {string} storeId 门店ID
   */
  async getAvailableCoupons(amount, storeId = null) {
    return await this.callFunction('coupon', 'available', {
      amount,
      storeId
    });
  }

  // ==================== 充值套餐包相关API ====================

  /**
   * 获取充值套餐包列表
   */
  async getRechargePackages() {
    return await this.callFunction('recharge_package', 'list', {});
  }

  /**
   * 获取充值套餐包详情
   * @param {string} packageId 套餐包ID
   */
  async getRechargePackageDetail(packageId) {
    return await this.callFunction('recharge_package', 'detail', { packageId });
  }

  // ==================== 管理员充值包管理接口 ====================
  
  /**
   * 获取管理员充值套餐包列表
   * @param {Object} params 查询参数
   * @returns {Promise} 套餐包列表
   */
  async getAdminRechargePackages(params = {}) {
    return await this.callFunction('cloud', 'admin/recharge_package/list', params);
  }

  /**
   * 添加充值套餐包
   * @param {Object} packageData 套餐包数据
   * @returns {Promise} 添加结果
   */
  async addRechargePackage(packageData) {
    return await this.callFunction('cloud', 'admin/recharge_package/add', packageData);
  }

  /**
   * 编辑充值套餐包
   * @param {string} packageId 套餐包ID
   * @param {Object} packageData 套餐包数据
   * @returns {Promise} 编辑结果
   */
  async editRechargePackage(packageId, packageData) {
    return await this.callFunction('cloud', 'admin/recharge_package/edit', { packageId, ...packageData });
  }

  /**
   * 切换充值套餐包状态
   * @param {string} packageId 套餐包ID
   * @returns {Promise} 切换结果
   */
  async toggleRechargePackageStatus(packageId) {
    return await this.callFunction('cloud', 'admin/recharge_package/toggle_status', { packageId });
  }

  /**
   * 删除充值套餐包
   * @param {string} packageId 套餐包ID
   * @returns {Promise} 删除结果
   */
  async deleteRechargePackage(packageId) {
    return await this.callFunction('cloud', 'admin/recharge_package/delete', { packageId });
  }

  // ==================== 员工相关API ====================

  /**
   * 获取员工列表
   * @param {string} storeId 门店ID
   * @param {string} grade 员工等级
   */
  async getEmployeeList(storeId = null, grade = null) {
    return await this.callFunction('employee', 'list', { storeId, grade });
  }

  /**
   * 获取员工详情
   * @param {string} employeeId 员工ID
   */
  async getEmployeeDetail(employeeId) {
    return await this.callFunction('employee', 'detail', { employeeId });
  }

  // ==================== 设备相关API ====================

  /**
   * 获取门店设备列表
   * @param {string} storeId 门店ID
   */
  async getDeviceList(storeId) {
    return await this.callFunction('device', 'getDeviceList', { storeId });
  }

  /**
   * 获取设备详情
   * @param {string} deviceId 设备ID
   */
  async getDeviceDetail(deviceId) {
    return await this.callFunction('device', 'getDeviceDetail', { deviceId });
  }

  /**
   * 控制设备开关
   * @param {string} deviceId 设备ID
   * @param {string} action 操作类型(on/off)
   * @param {number} duration 使用时长(分钟)
   */
  async controlDevice(deviceId, action, duration = 0, options = {}) {
    return await this.callFunction('device', 'controlDevice', { deviceId, action, duration, options });
  }

  /**
   * 更新设备状态
   * @param {string} deviceId 设备ID
   * @param {number} status 设备状态
   */
  async updateDeviceStatus(deviceId, status) {
    return await this.callFunction('device', 'updateDeviceStatus', { deviceId, status });
  }

  /**
   * 获取设备实时状态
   * @param {string} deviceId 设备ID
   */
  async getDeviceRealTimeStatus(deviceId) {
    return await this.callFunction('device', 'getDeviceRealTimeStatus', {
      deviceId
    });
  }

  /**
   * 获取门店设备实时状态
   * @param {string} storeId 门店ID
   */
  async getStoreDevicesRealTimeStatus(storeId) {
    return await this.callFunction('device', 'getStoreDevicesRealTimeStatus', {
      storeId
    });
  }

  // ==================== 设备订单相关API ====================

  /**
   * 创建设备使用订单
   * @param {string} deviceId 设备ID
   * @param {number} duration 使用时长（分钟）
   * @param {string} orderType 订单类型（normal/extend）
   * @param {string} parentOrderId 原订单ID（延时订单需要）
   */
  async createDeviceOrder(deviceId, duration, orderType = 'normal', parentOrderId = null) {
    return await this.callFunction('device_order', 'createDeviceOrder', {
      deviceId,
      duration,
      orderType,
      parentOrderId
    });
  }

  /**
   * 余额支付设备订单
   * @param {string} orderId 订单ID
   */
  async payDeviceOrderWithBalance(orderId) {
    return await this.callFunction('device_order', 'payDeviceOrderWithBalance', {
      orderId
    });
  }

  /**
   * 创建设备订单支付参数（微信支付）
   * @param {string} orderId 订单ID
   */
  async createDeviceOrderPayment(orderId) {
    if (setting.USE_SELF_BACKEND_PAYMENT && setting.API_BASE) {
      const js_code = await this.getWxLoginCode().catch(() => '');
      return await this.httpPost('/api/device_order/create_payment', { orderId, js_code });
    }
    return await this.callFunction('device_order', 'createDeviceOrderPayment', {
      orderId
    });
  }

  /**
   * 使用wxpayFunctions云函数创建微信支付订单（保留，但若启用自建后端则不再调用）
   * @param {Object} orderData 订单数据
   * @param {string} orderData.description 商品描述
   * @param {number} orderData.amount 支付金额（分）
   * @param {string} orderData.out_trade_no 商户订单号
   * @param {string} orderData.notify_url 回调通知URL
   */
  async createWxPayOrder(orderData) {
    if (setting.USE_SELF_BACKEND_PAYMENT && setting.API_BASE) {
      const js_code = await this.getWxLoginCode().catch(() => '');
      return await this.httpPost('/api/payment/wxpay_order', { ...orderData, js_code });
    }
    try {
      const result = await wx.cloud.callFunction({
        name: 'wxpayFunctions',
        data: {
          type: 'wxpay_order',
          ...orderData
        }
      });
      return result.result;
    } catch (error) {
      console.error('创建微信支付订单失败:', error);
      throw error;
    }
  }

  /**
   * 查询微信支付订单（通过商户订单号）
   * @param {string} outTradeNo 商户订单号
   */
  async queryWxPayOrderByOutTradeNo(outTradeNo) {
    if (setting.USE_SELF_BACKEND_PAYMENT && setting.API_BASE) {
      return await this.httpGet(`/api/payment/query_by_out_trade_no?out_trade_no=${encodeURIComponent(outTradeNo)}`);
    }
    try {
      const result = await wx.cloud.callFunction({
        name: 'wxpayFunctions',
        data: {
          type: 'wxpay_query_order_by_out_trade_no',
          out_trade_no: outTradeNo
        }
      });
      return result.result;
    } catch (error) {
      console.error('查询微信支付订单失败:', error);
      throw error;
    }
  }

  /**
   * 查询微信支付订单（通过微信订单号）
   * @param {string} transactionId 微信订单号
   */
  async queryWxPayOrderByTransactionId(transactionId) {
    if (setting.USE_SELF_BACKEND_PAYMENT && setting.API_BASE) {
      return await this.httpGet(`/api/payment/query_by_transaction_id?transaction_id=${encodeURIComponent(transactionId)}`);
    }
    try {
      const result = await wx.cloud.callFunction({
        name: 'wxpayFunctions',
        data: {
          type: 'wxpay_query_order_by_transaction_id',
          transaction_id: transactionId
        }
      });
      return result.result;
    } catch (error) {
      console.error('查询微信支付订单失败:', error);
      throw error;
    }
  }

  /**
   * 申请微信支付退款
   * @param {Object} refundData 退款数据
   * @param {string} refundData.out_trade_no 商户订单号
   * @param {string} refundData.out_refund_no 商户退款单号
   * @param {number} refundData.total 原订单金额（分）
   * @param {number} refundData.refund 退款金额（分）
   * @param {string} refundData.reason 退款原因
   */
  async createWxPayRefund(refundData) {
    if (setting.USE_SELF_BACKEND_PAYMENT && setting.API_BASE) {
      return await this.httpPost('/api/payment/refund', refundData);
    }
    try {
      const result = await wx.cloud.callFunction({
        name: 'wxpayFunctions',
        data: {
          type: 'wxpay_refund',
          ...refundData
        }
      });
      return result.result;
    } catch (error) {
      console.error('申请微信支付退款失败:', error);
      throw error;
    }
  }

  /**
   * 处理设备订单支付回调
   * @param {string} orderId 订单ID
   * @param {Object} paymentResult 支付结果
   */
  async handleDeviceOrderPaymentCallback(orderId, paymentResult) {
    if (setting.USE_SELF_BACKEND_PAYMENT && setting.API_BASE) {
      return await this.httpPost('/api/device_order/callback', { orderId, ...paymentResult });
    }
    return await this.callFunction('device_order', 'handleDeviceOrderPaymentCallback', {
      orderId,
      ...paymentResult
    });
  }

  // ==================== 基础HTTP方法（用于自建后端） ====================
  async httpGet(path) {
    const url = `${setting.API_BASE}${path}`;
    return await this.httpRequest('GET', url);
  }

  async httpPost(path, data = {}) {
    const url = `${setting.API_BASE}${path}`;
    return await this.httpRequest('POST', url, data);
  }

  async httpRequest(method, url, data = null) {
    return new Promise((resolve) => {
      wx.request({
        url,
        method,
        timeout: setting.API_REQUEST_TIMEOUT || 10000,
        header: {
          'Content-Type': 'application/json',
        },
        data,
        success: (res) => {
          // 统一兼容后端返回格式 { success, data, message/msg, code }
          const body = res.data || {};
          const code = (typeof body.code === 'number') ? body.code : res.statusCode;
          const hasBackendCode = typeof body.code === 'number';
          // success 判定优先级：显式 success -> 后端 code === 200 -> HTTP 2xx
          let successFlag;
          if (typeof body.success === 'boolean') {
            successFlag = body.success === true;
          } else if (hasBackendCode) {
            successFlag = body.code === 200;
          } else {
            successFlag = res.statusCode >= 200 && res.statusCode < 300;
          }
          const message = body.message || body.msg || (successFlag ? 'success' : '请求失败');
          // data 优先取 body.data；若为框架形式（含 code/msg），默认取 body.data；否则直接回传 body
          const normalizedData = (body && Object.prototype.hasOwnProperty.call(body, 'data')) ? (body.data || {}) : body;

          resolve({
            success: successFlag,
            data: normalizedData,
            message,
            code
          });
        },
        fail: (err) => {
          resolve({ success: false, message: err.errMsg || '网络错误', code: -1 });
        }
      });
    });
  }

  /**
   * 获取微信登录 code（JSAPI 下单用于换取 openid）
   */
  async getWxLoginCode() {
    return new Promise((resolve, reject) => {
      wx.login({
        timeout: 5000,
        success: (res) => resolve(res.code),
        fail: (err) => reject(err)
      });
    });
  }

  /**
   * 归一化微信支付参数，兼容不同后端返回字段差异
   * @param {Object} paymentParams 原始支付参数
   * @returns {Object} 归一化后的支付参数
   */
  normalizeWxPaymentParams(paymentParams) {
    if (!paymentParams || typeof paymentParams !== 'object') return paymentParams;
    const p = { ...paymentParams };
    // TEST_MODE: 兼容服务端返回 _isTestMode，统一为 testMode 供前端判断
    if (p._isTestMode === true && !p.testMode) p.testMode = true;
    // timeStamp 可能为数字或使用 timestamp 命名
    if (typeof p.timeStamp === 'number') p.timeStamp = String(p.timeStamp);
    if (!p.timeStamp && typeof p.timestamp !== 'undefined') p.timeStamp = String(p.timestamp);
    // 兼容 nonce 字段别名
    if (!p.nonceStr) {
      if (p.nonce) p.nonceStr = p.nonce;
      if (p.noncestr) p.nonceStr = p.noncestr;
    }
    // 兼容签名字段别名
    if (!p.paySign && p.sign) p.paySign = p.sign;
    // 若缺失 signType，但已生成 paySign，默认使用 RSA
    if (!p.signType && p.paySign) p.signType = (require('../setting/setting.js').PAYMENT_SIGN_TYPE || 'RSA');
    // 兼容 package 字段别名
    if (!p.package && p.packageValue) p.package = p.packageValue;
    // 若缺失 package，但存在预支付单号，自动构造
    if (!p.package) {
      if (p.prepay_id) p.package = `prepay_id=${p.prepay_id}`;
      else if (p.prepayId) p.package = `prepay_id=${p.prepayId}`;
    }
    // 去除字符串字段的首尾空格
    ['timeStamp','nonceStr','package','signType','paySign'].forEach(k => {
      if (typeof p[k] === 'string') p[k] = p[k].trim();
    });
    return p;
  }
}

const apiService = new ApiService();
module.exports = apiService;
